package com.hedgehoglab.fixx.wrapper;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;

import javax.ws.rs.core.MediaType;

public class Base<T>{
	private String fixxUrl = "http://localhost:8080/";
	protected WebResource resource;
    protected Client client;
    protected String authHeader;
    public static final String AUTHORIZATION = "Authorization";
	
	
	public List<T> makeGetRequest(String url,String type, boolean list){
		List<T> response = createResource()
			.path("/projects/1/issues")
			.header(AUTHORIZATION, authHeader)
			.type(MediaType.APPLICATION_XML_TYPE)
			.accept(MediaType.APPLICATION_XML_TYPE)
			.get(new GenericType<List<T>>(){});
		return response;
		
//		HttpClient client = new HttpClient();
//		client.getState().setCredentials(
//				new AuthScope("http://localhost/", 8080, AuthScope.ANY_REALM),
//                new UsernamePasswordCredentials("mark.forster", "user")
//        );
//		String response = null;
//
//        GetMethod get = new GetMethod(this.fixxUrl+url);
//        try {
//			client.executeMethod(get);
//			response = get.getResponseBodyAsString();
//		} catch (HttpException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return buildResponse(response, list);
		
	}

//	private List<T> buildResponse(String response,boolean list) {
////		Type listType = new TypeToken<T>() {}.getType();
////		Gson gson = new Gson();
////		T res = gson.fromJson(response, listType);
//		List<T> r = new ArrayList<T>();
////		r.add(res);
//		return r;
//	}

	public List<T> makeRequest(String method,String url,String type,boolean list){
		List<T> response = null;
		if(method=="get"){
			response = makeGetRequest(url,type,list);
		}
		
		return response;
	}
	
	
	public WebResource createResource() {
		client = Client.create();
        byte[] encoded = Base64.encodeBase64(("mark.forster:user").getBytes());
        authHeader = "Basic " + new String(encoded);
        WebResource resource = client.resource("http://localhost:8080/api");
        return resource;
    }

}
